package com.cbh.amadeus.client.handler;

import com.cbh.amadeus.client.config.SubscriberConfig;
import com.cbh.amadeus.client.core.Subscriber;
import com.cbh.amadeus.client.receiver.component.SubscriberComponent;
import com.cbh.amadeus.client.utils.ChannelReference;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author ChenBiHui
 * @date 2025/4/27
 */
@Slf4j
public class ReconnectHandler extends ChannelInboundHandlerAdapter {

    private final SubscriberComponent component;
    private final Integer sort;

    public ReconnectHandler(SubscriberComponent component, Integer sort) {
        this.component = component;
        this.sort = sort;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SubscriberConfig config = component.getConfig();
        Channel channel = ctx.channel();
        ChannelReference.remove(channel);
        channel.eventLoop().schedule(
                () -> {
                    log.info(
                            "===== EVENT [INACTIVE] Message center client has close will try to reconnect to the [{}:{}] =====",
                            config.getHost(),
                            config.getPort()
                    );
                    Subscriber.connect(component, sort);
                },
                config.getReconnectTimeSeconds(),
                TimeUnit.SECONDS
        );
        super.channelInactive(ctx);
    }
}
